//
//  ListServerVCNew.m
//  QGSPos
//
//  Created by vinh pham on 5/29/13.
//  Copyright (c) 2013 QGS Inc. All rights reserved.
//

#import "ListServerVCNew.h"
#import "ConfigServerVC.h"
#import "LoginViewController.h"
#import "VerifyAccountVC.h"

enum {
    kButtonTag = 100
};

@implementation ListServerVCNew
@synthesize indexServer;
@synthesize parent;
@synthesize arrayOfflineServer;
@synthesize arrayServer;
@synthesize mainTableView;
@synthesize btnClearDatabase;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        parent = _parent;
    }
    return self;
}

- (IBAction)btnClearDatabaseLocalClick:(id)sender {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Confirm!" message:@"Are you sure you want to clear the local database?" delegate:self cancelButtonTitle:nil otherButtonTitles:@"NO",@"YES", nil];
    [dialog show];
}

- (void)viewDidLoad
{
    // Do any additional setup after loading the view from its nib.

    [super viewDidLoad];
    self.navigationItem.title = @"List Server";
    if([[[UIDevice currentDevice] systemVersion]floatValue] >= 7)
    {
        btnClearDatabase.layer.borderWidth=1.0f;
        btnClearDatabase.layer.cornerRadius=5;
        btnClearDatabase.layer.borderColor = [[UIColor blackColor] CGColor];
    }
    btnClearDatabase.hidden = YES;
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-16, self.view.frame.size.height/2-16, 25, 25)];
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    myActivityView.hidesWhenStopped = YES;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    arrayOfflineServer = [[NSMutableArray alloc] init];
    arrayServer = [[NSMutableArray alloc] init];
    
    UIBarButtonItem *btnConfig = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(confirm)];
    self.navigationItem.rightBarButtonItem = btnConfig;
    
    [self setContentSizeForViewInPopover:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
    
    dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.list-server", NULL);
    dispatch_async(myQueue, ^(void) {

        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *serverLink = [userDefault objectForKey:SERVER_KEY];

        NSMutableArray *tmpArray = [userDefault objectForKey:ONLINE_SERVER_ARRAY];
        BOOL isFromServer = NO; //kiem tra neu get list server tu server thi gan = YES
        if (tmpArray == nil || [tmpArray count] == 0) {
//            NSString *pathServer = @"http://myqgs.com/ListServer.plist";
//            tmpArray = [NSMutableArray arrayWithContentsOfURL:[NSURL URLWithString:pathServer]];
            tmpArray = [NSMutableArray arrayWithCapacity:1];
            isFromServer = YES;
        }

        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if (tmpArray == nil) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Can't connect to our server. Please check your connection again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [dialog show];
            }
            
            if (isFromServer) {
                [tmpArray addObject:@"http://fms.qa.qgs.vn"];
                for (int i=0;i < [tmpArray count];i++) {
                    NSString *tmpLink = [tmpArray objectAtIndex:i];
                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:tmpLink,@"serverLink",[NSNumber numberWithBool:NO],@"isCheck",[NSNumber numberWithBool:NO],@"canEdit", nil];
                    [arrayServer addObject:dict];
                }
            }
            else {
                for (int i=0;i < [tmpArray count];i++) {
                    NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
                    [arrayServer addObject:dict];
                }
            }
            for (int i = 0; i < [arrayServer count]; i++) {
                NSMutableDictionary *dict = [arrayServer objectAtIndex:i];
                if([[dict objectForKey:@"serverLink"] isEqualToString:serverLink])
                {
                    [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];
                    break;
                }
            }
            
            [self.mainTableView reloadData];
            [myActivityView stopAnimating];
            
        });
    });
#if !OS_OBJECT_USE_OBJC
    dispatch_release(myQueue);
#endif
    myQueue = nil;
    
    dispatch_queue_t myQueue2 = dispatch_queue_create("com.myqgs.listOfflineServer", NULL);
    dispatch_async(myQueue2, ^(void) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

        NSString *remoteDatabaseLink;
        NSString *syncpoint = [[NSUserDefaults standardUserDefaults] objectForKey:CURRENT_REMOTE_DATABASE_URL];
        if (syncpoint.length > 0) {
            remoteDatabaseLink = [NSString stringWithFormat:@"%@",syncpoint];
        }
        else
            remoteDatabaseLink = @"";
        //get offline server array
        NSMutableArray *tmpOfflineServer = [userDefault objectForKey:OFFLINE_SERVER_ARRAY];
        for (int i = 0; i < [tmpOfflineServer count]; i++) {
            NSMutableDictionary *dict = [[tmpOfflineServer objectAtIndex:i] mutableCopy];
            if([[dict objectForKey:@"serverLink"] isEqualToString:remoteDatabaseLink])
            {
                [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];
                //                    break;
            }
            else {
                [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isCheck"];
                
            }
            [arrayOfflineServer addObject:dict];
        }
        
        BOOL isExisted = NO;
        //add new link to offline server
        for (int i=0;i < [arrayOfflineServer count];i++) {
            NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:i];
            if ([[dict objectForKey:@"serverLink"] isEqualToString:remoteDatabaseLink]) {
                isExisted = YES;
                break;
            }
        }
        if (![remoteDatabaseLink isEqualToString:@""] && !isExisted) {
            NSString *user = [userDefault objectForKey:CURRENT_USER_NAME_URL];
            NSString *pass = [userDefault objectForKey:CURRENT_USER_PASS_URL];
            if (user == nil)
                user = @"";
            if (pass == nil)
                pass = @"";
            BOOL isAuthen = NO;
            if (![user isEqualToString:@""]) {
                isAuthen = YES;
            }
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:remoteDatabaseLink,@"serverLink",[NSNumber numberWithBool:YES],@"isCheck",user,@"username",pass,@"password",[NSNumber numberWithBool:isAuthen],@"isAuthentication", nil];
            [arrayOfflineServer addObject:dict];
        }
        
        [userDefault setObject:arrayOfflineServer forKey:OFFLINE_SERVER_ARRAY];
        
        if ([arrayOfflineServer count] == 0)
            btnClearDatabase.hidden = YES;
        else
            btnClearDatabase.hidden = NO;
        
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [mainTableView reloadData];
        });
    });
#if !OS_OBJECT_USE_OBJC
    dispatch_release(myQueue2);
#endif
    myQueue2 = nil;
}

- (void) edit {
    if (!self.mainTableView.editing) {
        [self.mainTableView setEditing:YES animated:YES];
    }
    else {
        [self.mainTableView setEditing:NO animated:YES];
    }
}

- (void) editOffLineServer:(UIButton*)_sender {
    int index = _sender.tag - kButtonTag;
    NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:index];
    
    ConfigServerVC *controller = [[ConfigServerVC alloc] initWithNibName:@"ConfigServerVC" bundle:nil parent:self];
    
    controller.isEdit = YES;
    controller.isOnlineServer = NO;
    controller.inforDict = dict;
    [controller.view setNeedsDisplay];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void) editOnlineServer:(UIButton*)_sender {
    int index = _sender.tag - kButtonTag;
    NSMutableDictionary *dict = [arrayServer objectAtIndex:index];
    
    ConfigServerVC *controller = [[ConfigServerVC alloc] initWithNibName:@"ConfigServerVC" bundle:nil parent:self];
    
    controller.isEdit = YES;
    controller.isOnlineServer = YES;
    controller.inforDict = dict;
    [controller.view setNeedsDisplay];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void) confirm {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self performSelector:@selector(delayConfirm) withObject:self afterDelay:0.2];
}

- (void) delayConfirm {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    //set offline server link
    for (int i=0;i < [arrayOfflineServer count];i++) {
        NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:i];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        UITableViewCell *cell = [self.mainTableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            
            [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];

            [userDefaults setObject:[NSNumber numberWithInt:0] forKey:@"isFirstSync"];
            
            //check previous offline server and delete local database before setting new link
            NSString *previousDatabase = [userDefaults objectForKey:CURRENT_USER_NAME_URL];
            if ([previousDatabase isEqualToString:[dict objectForKey:@"username"]]) {
                
                NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"username"],@"username",[dict objectForKey:@"password"],@"password", nil];
                
                [[CouchBaseLiteLib sharedCouchBaseLite] setRemoteDatebaseUrl:[dict objectForKey:@"serverLink"] authenticateUser:userDict];
                
            }
            else {
                
                [[CouchBaseLiteLib sharedCouchBaseLite] deleteLocalDatabaseWithParent:nil];
                
                NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"username"],@"username",[dict objectForKey:@"password"],@"password", nil];
                
                [[CouchBaseLiteLib sharedCouchBaseLite] setRemoteDatebaseUrl:[dict objectForKey:@"serverLink"] authenticateUser:userDict];
            }
            break;
        }
        else {
            [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isCheck"];
        }
        [arrayOfflineServer replaceObjectAtIndex:i withObject:dict];
    }
    
    [userDefaults setObject:arrayOfflineServer forKey:OFFLINE_SERVER_ARRAY];
    
    
    BOOL isRequiredClearDatabase = NO;
    //set server link for online server
    for (int i=0;i < [arrayServer count];i++) {
        NSMutableDictionary *dict = [arrayServer objectAtIndex:i];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [self.mainTableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            
            //neu server online moi chon khac server truoc, thi yeu cau clear local database truoc khi doi server
            NSString *previousServerURL = [userDefaults objectForKey:SERVER_KEY];
            if (![previousServerURL isEqualToString:[dict objectForKey:@"serverLink"]] && [arrayOfflineServer count] > 0) {
                isRequiredClearDatabase = YES;
                break;
            }
            
            [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];
            [userDefaults setObject:[dict objectForKey:@"serverLink"] forKey:SERVER_KEY];
            [userDefaults setObject:arrayServer forKey:ONLINE_SERVER_ARRAY];
            
            [FMSServerAPI changeServerLink:[dict objectForKey:@"serverLink"]];
            //get virtual host, tach chuoi~ server link, chi lay phan: eg. demo.myqgs.com
            NSArray *tmpArray = [[dict objectForKey:@"serverLink"] componentsSeparatedByString:@"//"];
            NSEnumerator *nse = [tmpArray objectEnumerator];
            [nse nextObject];
            NSString *virtualHost = [nse nextObject];
            [userDefaults setObject:virtualHost forKey:VIRTUAL_HOST];
            //get companyId
            [[FMSLib shareClient] getDomainInfo:virtualHost successs:^(NSMutableDictionary *success){
                
                [userDefaults setObject:[success objectForKey:@"username"] forKey:NAME_AUTH];
                [userDefaults setObject:[success objectForKey:@"password"] forKey:PASS_AUTH];
                [userDefaults synchronize];
                
                [[FMSServerAPI shareClient] setUserName:[AppDelegate decryptInfo:[userDefaults objectForKey:NAME_AUTH] error:nil] password:[AppDelegate decryptInfo:[userDefaults objectForKey:PASS_AUTH] error:nil]];
                
            }failure:^(NSError *error){
                [userDefaults setObject:@"" forKey:NAME_AUTH];
                [userDefaults setObject:@"" forKey:PASS_AUTH];
                [userDefaults synchronize];
                
                [[FMSServerAPI shareClient] setUserName:@"" password:@""];
                
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Our server is temporary unavailable. Please retry later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [dialog show];
            }];
            break;
        }
        else {
            [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isCheck"];
        }
    }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    if (isRequiredClearDatabase) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Please clear your local database before choosing another server" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [dialog show];
        return;
    }
    [(LoginViewController*)parent dismissPopoverController];
}
- (void)reloadSynDataBase
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //set offline server link
    for (int i=0;i < [arrayOfflineServer count];i++) {
        NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:i];
        BOOL isCheck = [[dict objectForKey:@"isCheck"] boolValue];
        if (isCheck)
            [arrayOfflineServer removeObjectAtIndex:i];
    }
    [userDefaults setObject:arrayOfflineServer forKey:OFFLINE_SERVER_ARRAY];
    [mainTableView reloadData];
    
    if ([arrayOfflineServer count] == 0)
        btnClearDatabase.hidden = YES;
}

- (void) deleteLocalDatabase {
    
    [[CouchBaseLiteLib sharedCouchBaseLite] deleteLocalDatabaseWithParent:self];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:OFFLINE_SERVER_ARRAY];
    [arrayOfflineServer removeAllObjects];
    
    [(LoginViewController*)parent dismissPopoverController];
    
    [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:@"isInitDesignView"];
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {

        VerifyAccountVC *controller = [[VerifyAccountVC alloc] initWithNibName:@"VerifyAccountVC" bundle:nil parent:self];
        [controller.view setNeedsDisplay];
        controller.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:controller animated:YES completion:nil];
        controller.view.superview.frame = CGRectMake((1024-520)/2, (768-334)/2, 520, 234);
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0)
        return @"Online Server";
    else
        return @"Offline Server";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return [arrayServer count]+1;
    else
        return [arrayOfflineServer count]+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    NSMutableArray *tmpArray;
    if (indexPath.section == 0)
        tmpArray = arrayServer;
    else
        tmpArray = arrayOfflineServer;
    
    NSMutableDictionary *dict;
    if (indexPath.section == 1) {
        if (indexPath.row < [arrayOfflineServer count]) {
            dict = [tmpArray objectAtIndex:indexPath.row];
            cell.textLabel.text = [dict objectForKey:@"serverLink"];
            
            BOOL isCheck = [[dict objectForKey:@"isCheck"] boolValue];
            if (!isCheck)
                cell.accessoryType = UITableViewCellAccessoryNone;
            else
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            //add button edit
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(380, 5, 32, 32);
            [btn setBackgroundImage:[UIImage imageNamed:@"btnEditSmall.png"] forState:UIControlStateNormal];
            btn.tag = kButtonTag + indexPath.row;
            [btn addTarget:self action:@selector(editOffLineServer:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:btn];
        }
        else {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 35, 35)];
            imgView.image = [UIImage imageNamed:@"btnPlus.png"];
            [cell.contentView addSubview:imgView];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, 300, 30)];
            label.textAlignment = UITextAlignmentLeft;
            label.backgroundColor = [UIColor clearColor];
            label.font = [UIFont boldSystemFontOfSize:18];
            label.text = @"Add New Local Server URL";
            [cell.contentView addSubview:label];
        }
    }
    else {
        if (indexPath.row < [arrayServer count]) {
            dict = [tmpArray objectAtIndex:indexPath.row];
            cell.textLabel.text = [dict objectForKey:@"serverLink"];
            
            BOOL isCheck = [[dict objectForKey:@"isCheck"] boolValue];
            if (!isCheck)
                cell.accessoryType = UITableViewCellAccessoryNone;
            else
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            BOOL canEdit = [[dict objectForKey:@"canEdit"] boolValue];
            if (canEdit) {
                //add button edit
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(380, 5, 27, 27);
                [btn setBackgroundImage:[UIImage imageNamed:@"btnEditSmall.png"] forState:UIControlStateNormal];
                btn.tag = kButtonTag + indexPath.row;
                [btn addTarget:self action:@selector(editOnlineServer:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btn];
            }
        }
        else {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 35, 35)];
            imgView.image = [UIImage imageNamed:@"btnPlus.png"];
            [cell.contentView addSubview:imgView];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, 300, 30)];
            label.textAlignment = UITextAlignmentLeft;
            label.backgroundColor = [UIColor clearColor];
            label.font = [UIFont boldSystemFontOfSize:18];
            label.text = @"Add New Online Server URL";
            [cell.contentView addSubview:label];
        }
    }
    
    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row < [arrayOfflineServer count]) {
            NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:indexPath.row];
            BOOL isCheck = [[dict objectForKey:@"isCheck"] boolValue];
            if (isCheck)
                return UITableViewCellEditingStyleNone;
            else
                return UITableViewCellEditingStyleDelete;
        }
        else
            return UITableViewCellEditingStyleNone;
    }
    else {
        if (indexPath.row < [arrayServer count]) {
            NSMutableDictionary *dict = [arrayServer objectAtIndex:indexPath.row];
            BOOL canEdit = [[dict objectForKey:@"canEdit"] boolValue];
            if (canEdit)
                return UITableViewCellEditingStyleDelete;
            else
                return UITableViewCellEditingStyleNone;
        }
        else
            return UITableViewCellEditingStyleNone;
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        if (indexPath.section == 1) {
            if (indexPath.row < [arrayOfflineServer count]) {
                [arrayOfflineServer removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
                
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:arrayOfflineServer forKey:OFFLINE_SERVER_ARRAY];
                [userDefaults setObject:@"" forKey:CURRENT_REMOTE_DATABASE_URL];
            }
        }
        else {
            if (indexPath.row < [arrayServer count]) {
                [arrayServer removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
                
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:arrayServer forKey:ONLINE_SERVER_ARRAY];
                [userDefaults setObject:@"" forKey:SERVER_KEY];
            }
        }
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row < [arrayOfflineServer count]) {
            //select this server
            for (int i=0; i< [arrayOfflineServer count]; i++) {
//                NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:i];
//                [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isCheck"];
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                cell.accessoryType=UITableViewCellAccessoryNone;
            }
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
//            NSMutableDictionary *dict = [arrayOfflineServer objectAtIndex:indexPath.row];
//            [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];
//            [arrayOfflineServer setObject:dict atIndexedSubscript:indexPath.row];
        }
        else {
            //add new link
            ConfigServerVC *controller = [[ConfigServerVC alloc] initWithNibName:@"ConfigServerVC" bundle:nil parent:self];
            [controller.view setNeedsDisplay];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
    else {
        if (indexPath.row < [arrayServer count]) {
            for (int i=0; i< [arrayServer count]; i++) {
                NSMutableDictionary *dict = [arrayServer objectAtIndex:i];
                [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isCheck"];
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                cell.accessoryType=UITableViewCellAccessoryNone;
            }
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            NSMutableDictionary *dict = [arrayServer objectAtIndex:indexPath.row];
            [dict setObject:[NSNumber numberWithBool:YES] forKey:@"isCheck"];
        }
        else {
            //add new link
            ConfigServerVC *controller = [[ConfigServerVC alloc] initWithNibName:@"ConfigServerVC" bundle:nil parent:self];
            
            controller.isOnlineServer = YES;
            [controller.view setNeedsDisplay];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

- (void)dealloc {
}
- (void)viewDidUnload {
    [self setMainTableView:nil];
    [super viewDidUnload];
}
@end
